#include "rtc.h"
#include "time.h"
// #include "Blinker.h"

RtcDS1307<TwoWire> Rtc(Wire);
RtcDateTime ds1338;
RTC rtc;

uint8_t time_set = 0, time_sync = 0, force_update = 0;
const char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

void rtcInit(void)
{
    if(!Rtc.GetIsRunning())        
        Rtc.SetIsRunning(true);
}

uint8_t isTimeValid(void)
{
    if(ds1338.Year() > 2199)
        return YEAR_INVALID;
    else if(ds1338.Month() > 12)
        return MONTH_INVALID;
    else if(ds1338.Day() > 31)
        return DATE_INVALID;
    else if(ds1338.DayOfWeek() > 7)
        return WEEK_INVALID;
    else if(ds1338.Hour() > 23)
        return HOUR_INVALID;
    else if(ds1338.Minute() > 59)
        return MIN_INVALILD;
    else if(ds1338.Second() > 59)
        return SEC_INVALID;
    else
        return NONE_INVALID;
}

void rtcTask(void)
{
        String date_str;
        String time_str;
        uint8_t error_val = 5;

        if(time_set)
        {
            time_set = 0;
            date_str = String(monthName[rtc.month - 1]) + " " + String(rtc.date/10) + String(rtc.date%10) + " " + "20" + String(rtc.year);
            time_str = String(rtc.hour/10) + String(rtc.hour%10) + ":" + String(rtc.min/10) + String(rtc.min%10) + ":" + String(rtc.sec/10) + String(rtc.sec%10);
            Serial.print(date_str);
            Serial.println(time_str);
            RtcDateTime time_set = RtcDateTime(date_str.c_str(), time_str.c_str());
            Rtc.SetDateTime(time_set);
        }

        do
        {
            ds1338 = Rtc.GetDateTime();
            error_val-- ;    
        } while (isTimeValid() && error_val!=0);

        rtc.year = ds1338.Year();
        rtc.month = ds1338.Month();
        rtc.date = ds1338.Day();
        rtc.week = ds1338.DayOfWeek();
        rtc.hour = ds1338.Hour();
        rtc.min = ds1338.Minute();
        rtc.sec = ds1338.Second();
}
